<template>
  <el-dialog
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    title="远程图片"
    :visible.sync="dialogFormVisible"
    width="1200px"
    top="25px"
    class="explore"
    @close="close"
  >
    <div class="explore-body">
      <div class="paths">
        <div
          v-for="(item, index) of paths"
          :key="item"
          class="path-item"
          @click="handlePathClick(index)"
        >
          {{ item }}
        </div>
      </div>
      <div class="file-tree">
        <el-tree
          ref="tree"
          :default-expanded-keys="['/explore']"
          node-key="url"
          :load="loadNode"
          lazy
          :props="props"
          highlight-current
          accordion
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
          @node-click="handleNodeClick"
        ></el-tree>
      </div>
      <div v-loading="isLoading" class="file-list">
        <div
          v-for="(item, index) of list"
          :key="item.name"
          class="file-item"
          :title="item.name"
          :class="{ 'active-img': index === imgIndex }"
        >
          <el-image
            v-if="item.type === 'file'"
            class="file-label"
            :src="baseUrl + item.url"
            fit="contain"
            @click="handleImgClick(index)"
            @dblclick.native="handleImgDbclick(item)"
          ></el-image>
          <el-image
            v-else
            class="file-label"
            :src="folderSvg"
            fit="contain"
            @dblclick.native="handleDirDbclick(item.url)"
          ></el-image>

          <div class="file-name">
            {{ item.name }}
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
    <img-dialog ref="img-dialog" />
  </el-dialog>
</template>

<script>
  import request from '@/utils/request'
  import ImgDialog from '@/components/ImgDialog'
  import folderSvg from '@/assets/imgs/folder.svg'
  function getList(url) {
    return request({
      url: url,
      method: 'get',
    })
  }
  export default {
    name: 'Explore',
    components: {
      ImgDialog,
    },
    props: {
      rootName: {
        type: String,
        default: 'explore',
      },
      baseApi: {
        type: String,
        required: true,
      },
    },
    data() {
      const matchRes = this.baseApi.match(/http:\/\/(\d+\.?){4}:\d+/)
      let baseUrl = ''
      if (matchRes) {
        baseUrl = matchRes[0]
      }
      return {
        isLoading: false,
        dialogFormVisible: false,
        paths: [this.rootName],
        list: [],
        folderSvg,
        props: {
          label: 'name',
          isLeaf: 'leaf',
        },
        nodeTimer: null,
        store: {},
        url: '/' + this.rootName,
        nodeAction: '',
        imgIndex: -1,
        baseUrl,
      }
    },
    computed: {},
    watch: {
      url(url) {
        this.paths = url.split('/').slice(1)
        this.list = this.store[url] || []
        this.imgIndex = -1
      },
    },
    methods: {
      handleImgDbclick(item) {
        this.$refs['img-dialog'].showEdit(item.name, this.baseUrl + item.url)
      },
      handleImgClick(index) {
        if (this.imgIndex === index) return
        this.imgIndex = index
        console.log(index)
      },
      handlePathClick(index) {
        if (index + 1 === this.paths.length) return
        const url = '/' + this.paths.slice(0, index + 1).join('/')
        this.url = url
      },
      handleDirDbclick(url) {
        if (this.url === url) {
          this.imgIndex = -1
          return (this.list = this.store[url])
        }
        this.$refs.tree.setCurrentKey(url)
        setTimeout(() => {
          const dom = this.$refs.tree.$el.querySelector(
            '.el-tree-node.is-current'
          )
          dom.click()
        }, 0)
      },
      async loadNode(node, resolve) {
        if (node.level === 0) {
          return resolve([{ name: 'explore', url: '/explore' }])
        }
        this.url = node.key || this.url
        const api = this.baseApi.replace(/\/$/g, '')
        const { data } = await getList(api + this.url)
        this.imgIndex = -1
        this.list = data.filter((item) => {
          if (item.type === 'dir') return true
          return /\.(png|jpg|jpeg|gif|svg|bmp)$/.test(item.url)
        })

        this.store[this.url] = this.list
        data.forEach((item) => {
          item.isLeaf = item.type === 'file'
        })
        const children = data.filter((item) => item.type === 'dir')
        resolve(children)
      },
      handleNodeClick(data, node, comp) {
        if (this.nodeAction === 'collapse') return
        if (node.key !== this.url) {
          this.url = node.key
        }
      },
      handleNodeExpand(data, node, comp) {
        this.nodeAction = 'expand'
        this.url = node.key
      },
      handleNodeCollapse(data, node, comp) {
        this.nodeAction = 'collapse'
        if (node.parent && node.parent.key) {
          this.url = node.parent.key
        } else if (!node.parent.key) {
          this.url = '/' + this.rootName
        }
      },
      showEdit() {
        this.dialogFormVisible = true
      },
      close() {
        this.dialogFormVisible = false
      },
      confirm() {
        const file = this.list[this.imgIndex]
        if (!file) {
          this.$baseAlert('你还没有选择任何图片')
        }
        this.$emit('update-url', file.url)
        this.close()
      },
    },
  }
</script>

<style scoped>
  .explore-body {
    height: 650px;
    position: relative;
    /* overflow: auto; */
  }

  .explore >>> .el-dialog__body {
    padding: 0 20px;
  }

  .paths {
    height: 30px;
    border-bottom: 1px dashed #ccc;
    padding: 0 8px;
    line-height: 30px;
  }

  .file-tree {
    float: left;
    width: 210px;
    height: 619px;
    border-right: 1px dashed #ccc;
    box-sizing: border-box;
    padding: 8px 0;
    overflow: auto;
  }

  .file-list {
    width: 950px;
    float: right;
    height: 619px;
    overflow: auto;
    box-sizing: border-box;
    padding: 0 10px;
  }

  .path-item {
    float: left;
  }

  .path-item:not(:last-child) {
    font-weight: bold;
    cursor: pointer;
  }

  .path-item::after {
    content: '/';
    padding: 0 5px;
  }

  .path-item:last-child::after {
    content: '';
    padding: 0;
  }

  .file-item {
    width: 100px;
    height: 100px;
    float: left;
    margin: 8px;
    position: relative;
  }

  .file-name {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 25px;
    line-height: 25px;
    text-align: center;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .file-label {
    width: 100px;
    height: 75px;
    cursor: pointer;
  }

  .active-img {
    background-color: rgba(24, 144, 255, 0.3);
  }
</style>
